package olegroshka.src.com.bofa.olegroshka.datasource;

import java.util.Iterator;

import olegroshka.src.com.bofa.olegroshka.filter.Filter;

public class FilteringDataSource implements DataSource<Object[]> {

	private final Filter<Object>[] filters;
	private final DataSource<Object[]> dataSource;	


	public FilteringDataSource(
			DataSource<Object[]> dataSource,
			Filter<Object>[] filters) {
		this.dataSource = dataSource;
		this.filters = filters;
	}
	
	public Iterator<Object[]> iterator() {
		final Iterator<Object[]> iterator = dataSource.iterator();
		
		return new Iterator<Object[]>() {

			private Object[] current = null;
			public boolean hasNext() {
				if( current == null ) {
					current = next();
				}
				return current != null;
			}

			public Object[] next() {
				Object[] record = current;
				if( record != null ) {
					current = null;
				}

				while ( record == null && iterator.hasNext() ) {
					record = iterator.next();
					for (int i = 0; i < filters.length; i++) {
						Filter<Object> filter = filters[i];
						if (filter != null && !filter.accept(record[i])) {
							record = null;
							break;
						}
					}
				}
				return record;
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	public void begin() {
		dataSource.begin();
	}

	public void end() {
		dataSource.end();
	}

}
